﻿// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi 
// Source File Name:   ServiceLocator.java

package com.vandagroup.common.db;

import java.lang.reflect.Method;
import java.util.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ServiceLocator
{

    private static ServiceLocator _instance;
    private Map cache;
    private InitialContext initialContext;

    public static ServiceLocator getInstance()
    {
        return _instance;
    }

    private ServiceLocator()
        throws NamingException
    {
        initialContext = new InitialContext();
        cache = Collections.synchronizedMap(new HashMap());
    }

    public Object getEJBHome(String jndiHomeName)
        throws NamingException
    {
        if(cache.containsKey(jndiHomeName))
            return cache.get(jndiHomeName);
        if(initialContext != null)
        {
            Object nsObject = initialContext.lookup(jndiHomeName);
            if(nsObject instanceof EJBLocalHome)
            {
                cache.put(jndiHomeName, nsObject);
                return nsObject;
            } else
            {
                cache.put(jndiHomeName, nsObject);
                return nsObject;
            }
        } else
        {
            throw new NamingException("ServiceLocator:no InitialContext");
        }
    }

    public EJBObject create(String jndiHomeName)
        throws Exception
    {
        EJBHome home = (EJBHome)getEJBHome(jndiHomeName);
        Method method = home.getClass().getMethod("create", null);
        EJBObject obj = (EJBObject)method.invoke(home, null);
        return obj;
    }

    public DataSource getDataSource(String dataSourceName)
    {
        DataSource dataSource = null;
        if(cache.containsKey(dataSourceName))
        {
            dataSource = (DataSource)cache.get(dataSourceName);
        } else
        {
            try
            {
                dataSource = (DataSource)initialContext.lookup(dataSourceName);
            }
            catch(NamingException e)
            {
                e.printStackTrace();
            }
            cache.put(dataSourceName, dataSource);
        }
        return dataSource;
    }

    static 
    {
        try
        {
            _instance = new ServiceLocator();
        }
        catch(NamingException se)
        {
            se.printStackTrace();
        }
    }
}
